from appserver import db_store
import traceback

from models.entity.module import Module


class RoleWithModule(db_store.Model):
	__tablename__="roles_with_modules"
	__bind_key__="main"

	# id=db_store.Column(db_store.Integer,primary_key=True)
	role_id=db_store.Column(db_store.Integer,db_store.ForeignKey("roles.id"),nullable=False,primary_key=True)
	module_id=db_store.Column(db_store.Integer,db_store.ForeignKey("modules.id"),nullable=False,primary_key=True)

	def __repr__(self):
		return "<RoleWithModule %d+%d>" %(self.role_id,self.module_id)

	def save(self):
		if self.role_id is None:
			print("RoleWithButton save error: role_id cannot be empty")
			return -1
		if self.module_id is None:
			print("RoleWithButton save error: button_id cannot be empty")
			return -2
		try:
			db_store.session.add(self)
			db_store.session.commit()
			return 0
		except:
			print("table roles_with_buttons write error:\n--------------------\n%s\n----------------------" %(traceback.format_exc()))
			db_store.session.rollback()
			return -3

	def delete(self):
		# id=self.id
		try:
			db_store.session.delete(self)
			db_store.session.commit()
			return 0
		except:
			print("RoleWithButton(id=%d) delete  error:\n-------------------\n%s\n----------------------" (id,traceback.format_exc()))
			db_store.session.rollback()
			return -1
    #
	@staticmethod
	def get_role_with_module_by_role_id(id_num):
		return RoleWithModule.query.filter_by(role_id=id_num).first()

	@staticmethod
	def get_role_with_modules_by_role_id(id_num):
		connectors = RoleWithModule.query.filter_by(role_id=id_num).all()
		# print('connectors', connectors)
		rlist = []
		for item in connectors:
			# print('item', item)
			rlist.append(Module.query.filter_by(id=item.module_id).first())
		print('rlist', rlist)
		return rlist

	@staticmethod
	def add_modules_to_role_id(role_id, modules):
		# 向指定用户添加一组按钮
		# 用法:
		#       role_id 角色id
		#       modules 模型id的列表
		for item in modules:
			module_connector = RoleWithModule()
			module_connector.role_id = role_id
			module_connector.module_id = item
			if module_connector.save() != 0:
				return -1
		return 0
